import axios from 'axios'
import router from '@/router'
import { ElMessage } from 'element-plus'

let isRefreshing = false
let requests: Function[] = []

const service = axios.create({
  baseURL: 'http://101.37.86.17:80',
  timeout: 10000,
})


// 请求拦截器：自动带上 token
service.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('token')
    if (token) {
      config.headers!['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器：401 时尝试 refreshToken
service.interceptors.response.use(
  res => res,
  async error => {
    const originalRequest = error.config
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true

      const refreshToken = sessionStorage.getItem('refreshToken')
      if (!refreshToken) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
        return Promise.reject(error)
      }

      if (!isRefreshing) {
        isRefreshing = true
        try {
          const { data } = await service.post(
            '/per/user/refresh',
            { refreshToken }
          )
          if (data.code === '200') {
            const { token: newToken, refreshToken: newRefresh } = data.data
            sessionStorage.setItem('token', newToken)
            sessionStorage.setItem('refreshToken', newRefresh)

            // 重试队列里的请求
            requests.forEach(cb => cb(newToken))
            requests = []

            return service(originalRequest)
          } else {
            throw new Error('刷新失败')
          }
        } catch (e) {
          sessionStorage.removeItem('token')
          sessionStorage.removeItem('refreshToken')
          ElMessage.error('会话已失效，请重新登录')
          router.push('/login')
          return Promise.reject(e)
        } finally {
          isRefreshing = false
        }
      } else {
        // 刷新中，将请求挂起
        return new Promise(resolve => {
          requests.push((token: string) => {
            originalRequest.headers['Authorization'] = `Bearer ${token}`
            resolve(service(originalRequest))
          })
        })
      }
    }
    return Promise.reject(error)
  }
)

export default service
